/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.faare.service.services.trombinoscope;

import opiam.admin.faare.MessageUtil;
import opiam.admin.faare.config.TrombinoscopeConfig;
import opiam.admin.faare.config.javabeans.JBTrombiParams;
import opiam.admin.faare.exception.ServiceException;
import opiam.admin.faare.service.services.Service;

import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import javax.swing.JFrame;


/**
 * This service allows to generate PDF and graphic trombinoscopes.
 *
 */
public final class TrombinoscopeGenerator extends Service
{
    /** Utility class. */
    private TrombinoscopeGenerator()
    {
    }

    /** Service configuration file. */
    public static final String TROMBI_XML_FILE = "/config/service/trombinoscope/trombinoscope_conf.xml";

    /** Logger instance. */
    private static Logger _logger = Logger.getLogger(TrombinoscopeGenerator.class);

    /** Service instance. */
    private static TrombinoscopeGenerator _instance = new TrombinoscopeGenerator();

    /** Trombinoscope parameters. */
    private static JBTrombiParams trombiParams;

    /**
     * Service initialization.
     *
     * @param directory  Configuration files directory if any.
     *
     * @throws ServiceException  configuration error.
     */
    public static void initialize(String directory) throws ServiceException
    {
        //DW/2655/BeginPatch
        //TrombinoscopeGenerator.setServiceEnabled(true);
        _instance.setServiceEnabled(true);
        //DW/2655/EndPatch


        try
        {
            if (directory == null)
            {
                trombiParams = TrombinoscopeConfig.getInstance().readConfig(
                                 TrombinoscopeGenerator.class.getResourceAsStream(TROMBI_XML_FILE));
            }
            else
            {
                File f = new File(directory + TROMBI_XML_FILE);
                trombiParams = TrombinoscopeConfig.getInstance().readConfig(new FileInputStream(
                            f));
            }
        }
        catch (Exception e)
        {
            _logger.error(e);
            e.printStackTrace();
            throw new ServiceException(TROMBI_XML_FILE + " readConfig PROBLEM");
        }

        _logger.info(TROMBI_XML_FILE + " succesfully loaded");
    }

    //DW/2655/BeginPatch
    /**
     * This method indicates if the service is active or not.
     *
     * @return True if it is active, false otherwise.
     */
    public static boolean isServiceEnabled()
    {
        return _instance.serviceEnabled;
    }
    //DW/2655/EndPatch

    /**
     * Generate a graphical Trombinoscope.
     *
     * @param start  Start index in the list of entries.
     * @param cols   Number of columns.
     * @param nb     Number of entries to take into account.
     * @param entries    List of entries.
     * @param attribs    List of attributes to take into account.
     * @param imagetype  Type of image : gif, jpg, png.
     *
     * @return a list with : image as first element (java.io.ByteArrayOutputStream)
     *                  as second element, a java.util.Hashtable with for each
     *                  Trombinoscope cell :
     *                  the entry dn (OrgChartPanel.DN), the coordinates
     *                  (OrgChartPanel.XCOORD, OrgChartPanel.YCOORD,
     *                    OrgChartPanel.WIDTH and OrgChartPanel.HEIGHT)
     * @throws ServiceException in case of argument error
     */
    public static List generateTrombinoscope(int start, int cols, int nb,
        List entries, List attribs, String imagetype)
//DW/2642/BeginPatch
        throws ServiceException
//DW/2642/EndPatch
    {
//DW/2642/BeginPatch
        if ((start < 0) || (cols <= 0) || (nb <= 0) ||
            (attribs == null) || (entries == null) ||
            (start >= entries.size())
           )
        {
            throw new ServiceException(MessageUtil.formatMessage(
                    "MSG_ARGUMENT_INVALID"));
        }
//DW/2642/EndPatch
        Trombinoscope trombi = new Trombinoscope(start, cols, nb, entries,
                attribs);
        /* set configuration parameters */
        if (trombiParams.getPhotoColor() != null)
        {
            trombi.setPhotoColor(trombiParams.getPhotoColor().getColor());
        }

        if (trombiParams.getTextColor() != null)
        {
            trombi.setTextColor(trombiParams.getTextColor().getColor());
        }

        if (trombiParams.getTextAlignment() != null)
        {
            trombi.setTextAlignment(trombiParams.getTextAlignment());
        }

        if (trombiParams.getPhotoAttr() != null)
        {
            trombi.setPhotoAttr(trombiParams.getPhotoAttr());
        }

//DW/2615/BeginPatch
        if (trombiParams.getDefaultPhoto() != null)
        {
            //DW/2671/BeginPatch
            //trombi.setDefaultPhoto(trombiParams.getDefaultPhoto());
        	String path = (TrombinoscopeGenerator.class.getResource(TROMBI_XML_FILE)).toString();
        	if (path.indexOf("file:/") >= 0)
        	{
                    int nbsub = 5;

                    if (path.substring(7, 9).equals(":/"))
                    { /* this is Windows */
                        nbsub = 6;
                    }
        	    path = path.substring(nbsub);
        	}
        	int posWI = path.toUpperCase().indexOf("/WEB-INF/");
        	if (posWI > 0)
        	{
        		path = path.substring(0,posWI);
            	    trombi.setDefaultPhoto(path + trombiParams.getDefaultPhoto());
        	}
        	else
        	{
            	    trombi.setDefaultPhoto(trombiParams.getDefaultPhoto());
        	}
            //DW/2671/EndPatch
        }
//DW/2615/EndPatch

        trombi.doIt();

        JFrame aframe = new JFrame();
        aframe.getContentPane().add(trombi);
        aframe.pack();

//DW/2644/BeginPatch
        List result = trombi.doPrint(imagetype);
        aframe.dispose();
        return result;
//DW/2644/EndPatch
    }

    /**
     * Generate a PDF Trombinoscope.
     *
     * @param start  Start index in the list of entries.
     * @param cols   Number of columns.
     * @param nb     Number of entries to take into account.
     * @param entries  List of entries.
     * @param attribs  List of attributes to take into account.
     *
     * @return a PDF stream containing the Trombinoscope.
     * @throws ServiceException in case of argument error
     */
    public static ByteArrayOutputStream generatePdfTrombinoscope(int start,
        int cols, int nb, List entries, List attribs)
//DW/2642/BeginPatch
        throws ServiceException
//DW/2642/EndPatch
    {
//DW/2642/BeginPatch
        if ((start < 0) || (cols <= 0) || (nb <= 0) ||
            (attribs == null) || (entries == null) ||
            (start >= entries.size())
           )
        {
            throw new ServiceException(MessageUtil.formatMessage(
                    "MSG_ARGUMENT_INVALID"));
        }
//DW/2642/EndPatch
        Trombinoscope trombi = new Trombinoscope(start, cols, nb, entries,
                attribs);
        /* set configuration parameters */
        if (trombiParams.getPhotoColor() != null)
        {
            trombi.setPhotoColor(trombiParams.getPhotoColor().getColor());
        }

        if (trombiParams.getTextColor() != null)
        {
            trombi.setTextColor(trombiParams.getTextColor().getColor());
        }

        if (trombiParams.getTextAlignment() != null)
        {
            trombi.setTextAlignment(trombiParams.getTextAlignment());
        }

        if (trombiParams.getPhotoAttr() != null)
        {
            trombi.setPhotoAttr(trombiParams.getPhotoAttr());
        }

//DW/2615/BeginPatch
        if (trombiParams.getDefaultPhoto() != null)
        {
            //DW/2671/BeginPatch
            //trombi.setDefaultPhoto(trombiParams.getDefaultPhoto());
        	String path = (TrombinoscopeGenerator.class.getResource(TROMBI_XML_FILE)).toString();
        	if (path.indexOf("file:/") >= 0)
        	{
                    int nbsub = 5;

                    if (path.substring(7, 9).equals(":/"))
                    { /* this is Windows */
                        nbsub = 6;
                    }
        	    path = path.substring(nbsub);
        	}
        	int posWI = path.toUpperCase().indexOf("/WEB-INF/");
        	if (posWI > 0)
        	{
        		path = path.substring(0,posWI);
            	trombi.setDefaultPhoto(path + trombiParams.getDefaultPhoto());
        	}
        	else
        	{
            	trombi.setDefaultPhoto(trombiParams.getDefaultPhoto());
        	}
            //DW/2671/EndPatch
            
        }
//DW/2615/EndPatch

        trombi.doIt();

        JFrame aframe = new JFrame();
        aframe.getContentPane().add(trombi);
        aframe.pack();

//DW/2644/BeginPatch
        ByteArrayOutputStream result = trombi.doPrintAsPdf();
        aframe.dispose();
        return result;
//DW/2644/EndPatch
    }
}
